from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.pagination import PageNumberPagination
from django.shortcuts import get_object_or_404
from django.db import transaction
from .models import Comment, Like, Bookmark
from stories.models import Story
from .serializers import CommentSerializer, CommentCreateSerializer


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def like_story(request, story_id):
    """点赞/取消点赞故事"""
    story = get_object_or_404(Story, id=story_id)
    
    try:
        with transaction.atomic():
            like = Like.objects.filter(user=request.user, story=story).first()
            
            if like:
                like.delete()
                story.likes = max(0, story.likes - 1)
                story.save(update_fields=['likes'])
                action = 'unliked'
                is_liked = False
            else:
                Like.objects.create(user=request.user, story=story)
                story.likes += 1
                story.save(update_fields=['likes'])
                action = 'liked'
                is_liked = True
            
            return Response({
                'success': True,
                'message': '操作成功',
                'data': {
                    'story_id': story.id,
                    'action': action,
                    'likes': story.likes,
                    'is_liked': is_liked
                }
            })
    except Exception as e:
        return Response({
            'success': False,
            'message': f'操作失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_comment(request, story_id):
    """添加评论"""
    story = get_object_or_404(Story, id=story_id)
    
    serializer = CommentCreateSerializer(data=request.data)
    
    if not serializer.is_valid():
        return Response({
            'success': False,
            'message': '验证失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)
    
    comment = Comment.objects.create(
        story=story,
        author=request.user,
        content=serializer.validated_data['content']
    )
    
    comment_data = CommentSerializer(comment, context={'request': request}).data
    
    return Response({
        'success': True,
        'message': '评论添加成功！',
        'data': comment_data
    }, status=status.HTTP_201_CREATED)


@api_view(['GET'])
def get_story_comments(request, story_id):
    """获取故事的评论列表"""
    story = get_object_or_404(Story, id=story_id)
    
    comments = Comment.objects.filter(story=story).select_related('author').order_by('-created_at')
    
    paginator = PageNumberPagination()
    page = paginator.paginate_queryset(comments, request)
    
    serializer = CommentSerializer(page, many=True, context={'request': request})
    
    return paginator.get_paginated_response({
        'success': True,
        'data': {
            'items': serializer.data,
            'total': comments.count()
        }
    })


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_comment(request, story_id, comment_id):
    """删除评论"""
    comment = get_object_or_404(Comment, id=comment_id, story_id=story_id)
    
    if comment.author != request.user and request.user.role != 'admin':
        return Response({
            'success': False,
            'message': '无权限删除其他用户的评论'
        }, status=status.HTTP_403_FORBIDDEN)
    
    comment.delete()
    
    return Response({
        'success': True,
        'message': '评论删除成功！'
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def like_comment(request, story_id, comment_id):
    """点赞/取消点赞评论"""
    comment = get_object_or_404(Comment, id=comment_id, story_id=story_id)
    
    try:
        with transaction.atomic():
            like = Like.objects.filter(user=request.user, comment=comment).first()
            
            if like:
                like.delete()
                comment.likes = max(0, comment.likes - 1)
                comment.save(update_fields=['likes'])
                action = 'unliked'
            else:
                Like.objects.create(user=request.user, comment=comment)
                comment.likes += 1
                comment.save(update_fields=['likes'])
                action = 'liked'
            
            return Response({
                'success': True,
                'message': '操作成功',
                'data': {
                    'comment_id': comment.id,
                    'action': action,
                    'likes': comment.likes
                }
            })
    except Exception as e:
        return Response({
            'success': False,
            'message': f'操作失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def bookmark_story(request, story_id):
    """收藏/取消收藏故事"""
    story = get_object_or_404(Story, id=story_id)
    
    try:
        with transaction.atomic():
            bookmark = Bookmark.objects.filter(user=request.user, story=story).first()
            
            if bookmark:
                # 已收藏，取消收藏
                bookmark.delete()
                action = 'unbookmarked'
                is_bookmarked = False
                message = '已取消收藏'
            else:
                # 未收藏，添加收藏
                Bookmark.objects.create(user=request.user, story=story)
                action = 'bookmarked'
                is_bookmarked = True
                message = '收藏成功'
            
            return Response({
                'success': True,
                'message': message,
                'data': {
                    'story_id': story.id,
                    'action': action,
                    'is_bookmarked': is_bookmarked
                },
                'is_bookmarked': is_bookmarked  # 前端直接使用
            })
    except Exception as e:
        return Response({
            'success': False,
            'message': f'操作失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
